How to do spatial join in Python


GIS in Python: Spatial Join

Spatial join is a method to combine information from different shapefiles by using spatial relationships as the join key. For example, you would like to study which county in California state has the most socioeconomically disadvantaged students, but you have two shapefiles on hand, one is a California counties shapefile without the attribute of the number of socioeconomically disadvantaged students and the other is a shapefile of California public school locations supplemented with the schools' demographic information in 2019. Let’s conduct this analysis using Python and the geopandas package. You can use the read_file() method from the geopandas package to read shapefiles, convert the coordinate reference systems of the shapefiles to an appropriate one for the geography of your data by using the to_crs() method, and then use the sjoin() method to join the shapefiles based on their spatial relationship to one another.


Part A: Install and Launch Jupyter Notebook via Anaconda

If you already have Anaconda downloaded and installed, you can skip Part A and directly start the analysis in Part B. Make sure you also have packages pandas, geopandas of version 0.7 or higher, matplotlib, and descartes installed in the environment where you would like to conduct this analysis. Note starting with the version 0.7, geopandas made a big change in Coordinate Reference System representation and hence some code syntax differs before and after version 0.7, as described here and here. As our tutorial writes in new version syntax, please make sure your geopandas is of version 0.7 or later in order to run the code with no error. You may check the version of geopandas and upgrade it within your environment either in Anaconda Navigator or in your terminal window.

1) First, download Anaconda. Anaconda is a free and open-source distribution of Python. You can use Anaconda to install IDEs (integrated development environments where you can write and run code) and packages like Pandas and Geopandas. Go to the link to download Anaconda, https://www.anaconda.com/products/individual, and then open the .exe file that was downloaded and follow the instructions in the installation wizard prompt.


2) Once installation is complete, open Anaconda Navigator and create a new environment for your project. A Conda environment is a directory that contains a specific collection of Conda packages that you have installed. Conda has a default environment called 'base' that includes a Python installation and some core system libraries and dependencies of Conda. It is a “best practice” to avoid installing additional packages into your base environment, and, instead, create an isolated environment to manage packages and dependencies in a new project.

Click on the Environments selection in the left sidebar menu and then click on the 'Create' at the bottom. This will open a dialog box prompting you to create a name for the new environment. You can give any name for your new environment. Here, we use 'GIS_in_Python' as the environment name. Then click the 'Create' button within the dialog box to finish the creation.


3) Once you have your project environment set up, click on the arrow to the right of your new environment, 'GIS_in_Python' in this example, and select Open Terminal. This will give you access to the command line interface on your computer in a window.


4) Install the packages/libraries necessary for the analysis by entering the following commands in the opened terminal, one line at a time:
conda install pandas
conda install geopandas
conda install matplotlib
conda install descartes


5) Once you have those libraries all installed, select the new environment, 'GIS_in_Python' in this example, in the 'Applications on' dropdown menu, and then click "install" and "launch" under Jupyter Notebook. Jupyter Notebook will open in your web browser (it does not require the internet to work).


6) In Jupyter Notebook, navigate to the folder where you saved the code file you plan to use and open the .ipynb file (the extension for Jupyter Notebook files written in Python) to run it in the Notebook. If you would like to create a new .ipynb file, browse to the folder in which you would like to save your Notebook, then click the "New" dropdown button on the top-right and select "Python 3". Your new Notebook will open in a new tab in your browser. If you want to create a new directory using the Jupyter Notebook dashboard, click the "New" dropdown button and then select "Folder". To add files from your local machine, click the "Upload" button on the top-right to open a file chooser window and then choose the file you wish to upload.


Part B: Read Data File and Perform Spatial Join

1) Import necessary packages/libraries.


2) Use the gpd.read_file() function from the geopandas package to read the shapefile. Optionally, you can use the head() method to return the first 5 rows of the GeoDataFrame, and use the .shape attribute to check the number of rows and columns of the GeoDataFrame in the returned tuple (number of rows, number of columns). For this example, the number of rows of the 'CA_schools' and the 'CA_counties' suggest that there are 10051 schools and 58 counties in California state in 2019.

Let’s look at the shape of the shapefiles for 'CA_schools' and 'CA_counties'.

You may also use matplotlib for plotting to generate an overview of your GeoDataFrame.


3) Before spatial join, use the .crs attribute to check the current Coordinate Reference System (CRS)/projection of your spatial datasets, and if they are not projected into the same coordinate reference system, use the to_crs() method to re-project the data to a projection appropriate for the geographical area of your data. This is because the geopandas package can only carry out a spatial join between layers that are in the same projected coordinate.

In this example, 'CA_schools' and 'CA_counties' are the two GeoDataFrame that we need to examine their projections (.crs). Since the CRS of the two GeoDataFrames are different, EPSG:4326 for the 'CA_schools' and EPSG:3857 for the 'CA_counties', we must convert the CRS. A bit of research suggests that EPSG:3310 would be an appropriate projection for California state. Therefore, we convert the CRS of 'CA_schools' and 'CA_counties' to EPSG:3310 (.to_crs('epsg:3310')).

For more information and resources on coordinate systems and map projections, please see Appendix 1 in NYU Data Services’ QGIS tutorial, which is available here.

4) Once the two GeoDataFrames have been converted into the same coordinate reference system, you can use the sjoin() method to carry out a spatial join between the two layers.

Optionally, to have a sanity-check of the spatial join result, you can use the .shape attribute to check the number of rows and columns, and use the head() method to return the first 5 rows of geometry column of the new GeoDataFrame. The output of the sjoin() operation is a GeoDataFrame with one row for each school that is located inside a county (one of the 10051 schools is discarded), the polygon geometry of the counties that contain the schools, and all of the attribute columns from both input GeoDataFrames (48 + 18 = 66).

5) Now that the attribute tables of the two spatial objects have been joined together, we would like to determine how many socioeconomically disadvantaged students were in each county of California state in 2019. We can use the groupby() method to group the GeoDataFrame 'join' by state names ( ['NAME'] ), and then use the sum() method to sum the values in the column SEDcont ( ['SEDcont'] ). To have a look at the top few counties with the most socioeconomically disadvantaged students, we can use the sort_values() method with the argument ascending = False to sort the results to be descending, and then use the head() method to show the first five rows.

In conclusion, the calculation result shows that the county having the most socioeconomically disadvantaged students in 2019 is Los Angeles county.